package sync

import (
	"fmt"

	"encoding/json"
	"io/ioutil"
	"net/http"
)

type Results struct {
	Version int64
	Entries []string
}

type feed struct {
	baseURI string
	id      string
}

func Feed(baseuri, id string) *feed {
	return &feed{baseuri, id}
}

func get(url string) ([]byte, error) {

	r, err := http.Get(url)

	if err != nil {
		return nil, err
	}

	body, err := ioutil.ReadAll(r.Body)

	if err != nil {
		return nil, err
	}

	return body, nil
}

func (f *feed) Subscribe(since int64, onupdate func(int64), foreach func(string)) error {

	for {

		body, err := get(fmt.Sprintf("%s/feed?id=%s&since=%d&block=true", f.baseURI, f.id, since))

		var results Results

		err = json.Unmarshal(body, &results)

		if err != nil {
			return err
		}

		if onupdate != nil {
			onupdate(since)
		}

		if foreach != nil {
			for _, entry := range results.Entries {

				foreach(entry)
			}
		}

		since = results.Version + int64(1)
	}

	panic("impossible")
}
